package com.figure.web.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.nio.charset.Charset;

public class FastJsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private static final SerializerFeature[] CONFIG = new SerializerFeature[]{
            //SerializerFeature.WriteNullBooleanAsFalse,//boolean为null时输出false
//            SerializerFeature.WriteMapNullValue, //输出空置的字段
            //SerializerFeature.WriteNonStringKeyAsString,//如果key不为String 则转换为String 比如Map的key为Integer
//            SerializerFeature.WriteNullListAsEmpty//,//list为null时输出[]
            SerializerFeature.NotWriteRootClassName
            //SerializerFeature.WriteNullNumberAsZero,//number为null时输出0
            //SerializerFeature.WriteNullStringAsEmpty//String为null时输出""
    };

    public FastJsonHttpMessageConverter(){
        super(new MediaType("application", "json", DEFAULT_CHARSET));
    }

    @Override
    protected Object readInternal(Class<? extends Object> clazz,
                                  HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

    	String jsonStr = IOUtils.toString(inputMessage.getBody(), DEFAULT_CHARSET.name());
        try{
			return JSON.parseObject(jsonStr, clazz);
        }catch(Exception e){
            throw new HttpMessageNotReadableException("Could not read JSON: " + jsonStr, e);
        }

    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    protected void writeInternal(Object t, 
                                 HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

        String json = JSON.toJSONStringWithDateFormat(t, "yyyy-MM-dd HH:mm:ss");

        outputMessage.getBody().write(json.getBytes());
    }

}
